<template>
  <view>
    <button type="primary" open-type="getUserInfo" @getuserinfo="getUser">使用微信登录</button>
  </view>
</template>

<script>
var _self, pageOptions, session_key, openid;
export default {
  data() {
    return {
      session_key: "",
      openid: ""
    };
  },

  methods: {
    getUser() {
      this.request({
        url: this.apiServer + "/user/findUserByOpenId?openId=" + this.openid
      }).then(res => {
        console.log(res);
        uni.showToast({ title: res.msg });
        uni.setStorageSync("user", res.data);
        // uni.setStorageSync("u_id", res.id);
        // uni.setStorageSync("nickname", res.nickname);
        // uni.setStorageSync("avatarurl", res.avatarurl);
        
        uni.switchTab({ url: "/pages/home/index" });
      });
    }
  },
  onLoad: function(options) {
    _self = this;
    //pageOptions = options;
    // 调用 微信 login 获取 code
    uni.login({
      success: res => {
        uni.request({
          url: _self.apiServer + "/user/commitCode?code=" + res.code,
          success: session => {
            this.session_key = session.data.session_key;
            this.openid = session.data.openid;
            this.getUser();
          },
          fail:res=>{
            uni.showToast({
              title:res,
              icon:"none",
              duration:2000
            })
          }
        });
      }
    });
  }
};
</script>
<style>
</style>